#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2015  Data Enlighten Technology (Beijing) Co.,Ltd


import base64
import json
import Lib.Logger.log4py as logging
from mj_parser import common_errors
import sys
import traceback
import os


class GmParserWeb:
    default_result = {
        "body":            '',
        "series":             '',
        "mod_year":        '',
        "year":  '',
        "pr":       ''
    }

    def __init__(self, root_dir):
        self.root_dir = root_dir
        self.logger = logging.get_logger("crawler", "GmParserWeb")

    def parse(self, file_name):
        b = common_errors.ERR_SUCCESS
        result_list = self.get_default_result()
        try:
            if not os.path.exists(file_name):
                b = common_errors.ERR_UNKNOWN
                return b, result_list

            fobj = open(file_name, encoding='utf_8_sig')
            f_buff = fobj.read()
            catalog = json.loads(f_buff)
            if catalog['body'] is None and catalog['series'] is None and catalog['vin'] is None and catalog['modelYear'] is None and catalog['rpos'] is None:
                b = common_errors.ERR_NO_VIN
                return b, result_list

            result_list['body'] = catalog['body']
            result_list['series'] = catalog['series']
            result_list['mod_year'] = catalog['modelYear'] if catalog['modelYear'][2] != '3' else catalog['modelYear'][:2] + '0' + catalog['modelYear'][3]
            result_list['year'] = catalog['productMonth']
            result_list['pr'] = self.get_pr_info(catalog['rpos'])

            result_list['raw_content'] = base64.b64encode(f_buff.encode('utf-8')).decode('utf-8')

        except Exception as ex:
            try:
                b = common_errors.ERR_UNKNOWN
                exc_info = sys.exc_info()
                self.logger.error(ex)
            finally:
                traceback.print_exception(*exc_info)
                del exc_info
        return b, result_list

    def get_pr_info(self, rpos):
        result_list = []
        for pr_item in rpos:
            result_list.append(pr_item["optionCode"])
        return '|'.join(result_list)

    def get_default_result(self):
        return GmParserWeb.default_result.copy()

if __name__ == '__main__':
    per = GmParserWeb('.\\')
    per.parse('.\\gm\\LSGNB83L5HA032814.json',)

